package com.my.swas.photo.utils;

import cn.hutool.core.io.FileUtil;
import com.baidu.aip.bodyanalysis.AipBodyAnalysis;
import com.baidu.aip.util.Util;
import com.my.swas.photo.config.YamlConfigUtil;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description:
 * @author: :MaYong
 */
@Slf4j
public class BaiDuBodyAnalysisUtil {

    private static Logger logger = LoggerFactory.getLogger(BaiDuBodyAnalysisUtil.class);

    private static String APP_ID = "17176280";
    private static String API_KEY = "4Q7p6cbh8xb1oTX4X2EK3D5C";
    private static String SECRET_KEY = "GQ0dq9DgmuQc1DxQxFMq64lGGA9aLP18";


    // 并发访问锁
    private static final ReentrantLock lock = new ReentrantLock();
    private static AipBodyAnalysis aipBodyAnalysisInstance = null;

    // 静态初始化
    static {
        if (aipBodyAnalysisInstance == null) {
            init();
        }
    }

    public BaiDuBodyAnalysisUtil() {
    }

    /**
     * @author MaYong
     */
    private static void init() {
        lock.lock();
        try {
            if (aipBodyAnalysisInstance == null) {
                aipBodyAnalysisInstance = new AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY);
                aipBodyAnalysisInstance.setConnectionTimeoutInMillis(3000);
                aipBodyAnalysisInstance.setSocketTimeoutInMillis(60000);
                log.info("百度：AipBodyAnalysis 接口初始化完毕");
            }
        } finally {
            lock.unlock();
        }
    }

    /**
     * 取得实例
     *
     * @return 配置文件实例
     */
    public static AipBodyAnalysis getInstance() {
        if (aipBodyAnalysisInstance == null) {
            init();
        }
        return aipBodyAnalysisInstance;
    }

    /**
     * 获取前景人像图（透明背景）
     *
     * @param imageUrl
     */
    public static boolean bodySeg(String imageUrl) {
        String type = "foreground";
        HashMap<String, String> options = new HashMap<>();
        options.put("type", type);
        JSONObject res;
        if (CommonUtil.isHttpUrl(imageUrl)) {
            byte[] b = CommonUtil.readFileStream(imageUrl);
            res = aipBodyAnalysisInstance.bodySeg(b, options);
        } else {
            res = aipBodyAnalysisInstance.bodySeg(imageUrl, options);
        }
        if (res.has("error_code")) {
            logger.info("人像分割异常,异常编号:{},异常信息：{}", res.get("error_code"), res.get("error_msg"));
            return false;
        }
        Boolean bool = CommonUtil.saveImage(res.getString(type),"");
        if (!bool) {
            return false;
        }
        return true;
    }

    /**
     * 获取前景人像图（透明背景）
     *
     * @param file
     */
    public static String bodySeg(File file,String tempdir) {
        String type = "foreground";
        HashMap<String, String> options = new HashMap<>();
        options.put("type", type);
        byte[] b = CommonUtil.readFileStream(file);
        JSONObject res = aipBodyAnalysisInstance.bodySeg(b, options);

        if (res.has("error_code")) {
            logger.info("人像分割异常,异常编号:{},异常信息：{}", res.get("error_code"), res.get("error_msg"));
            return null;
        }
        String tempPath = tempdir+File.separator+FileUtil.mainName(file)+"."+ FileUtil.extName(file);
        Boolean bool = CommonUtil.saveImage(res.getString(type),tempPath);
        if (!bool) {
            return null;
        }
        return tempPath;
    }


    /**
     * 获取关键点坐标
     * @param imageUrl
     */
    public static JSONObject bodyPointDiscern(String imageUrl) throws IOException {
        log.info("获取人体关键点图片路径：{}",imageUrl);
        HashMap<String, String> options = new HashMap<>();
        JSONObject res = aipBodyAnalysisInstance.bodyAnalysis(Util.readFileByBytes(imageUrl), options);
        if (res.has("error_code")) {
            logger.info("获取关键点识别异常,异常编号:{},异常信息：{}", res.get("error_code"), res.get("error_msg"));
            return null;
        }
        logger.info("关键点：{}", res);
        JSONArray jsonArray = res.getJSONArray("person_info");
        if(jsonArray == null || jsonArray.length() <= 0){
            return null;
        }

        JSONObject bodyPartsJson = jsonArray.getJSONObject(0).getJSONObject("body_parts");
        return bodyPartsJson;
    }

}
